<template>
  <div class="dashboard-container">
    <el-table
      :data="listData"
      style="width: 100%">
      <el-table-column
        prop="user_id"
        label="用户id"
        width="180">
      </el-table-column>
      <el-table-column
        prop="user_name"
        label="用户名"
        width="180">
      </el-table-column>
      <el-table-column
        prop="nickname"
        label="姓名"
        width="180">
      </el-table-column>
      <el-table-column
        prop="password"
        label="密码"
        width="180">
      </el-table-column>
      <el-table-column
        prop="register_time"
        label="注册时间"
        width="180">
      </el-table-column>
      <el-table-column
        :filters="[{ text: 'admin', value: 'admin' }, { text: 'user', value: 'user' }]"
        :filter-method="filterTag"
        prop="role"
        label="权限"
        width="180">
      </el-table-column>
      <el-table-column
        prop="address"
        label="地址"
        width="180">
      </el-table-column>
      <el-table-column 
        fixed="right"
        label="操作"
        width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="danger"
            @click="Delete(scope.row.user_id,scope.$index)">删除</el-button>
          <el-button
            v-if="scope.row.role=='user'"
            size="mini"
            @click="update(scope.row,scope.$index)">设为管理员</el-button>
          <el-button
            v-else
            size="mini"
            @click="disUpdate(scope.row,scope.$index)">撤销管理员</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {getUsers,deleteUser,updateUser} from '../../api/user'

export default {
  name: 'Dashboard',
  data(){
    return {
      listData:[],
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  created(){
    getUsers().then(res=>{
      console.log(res.data)
      res.data.map(item=>{
        item.address=item.address.join(',')
      })
      this.listData = res.data
    })
  },
  methods: {
      update(data,index) {
        console.log(data)
        updateUser(data.user_id,data.user_name,data.password,data.nickname,'admin',data.phone,data.address).then(res=>{
          this.listData[index].role = 'admin'
        })
      },
      disUpdate(data,index) {
        console.log(data)
        updateUser(data.user_id,data.user_name,data.password,data.nickname,'user',data.phone,data.address).then(res=>{
          this.listData[index].role = 'user'
        })
      },
      Delete(user_id,index) {
        deleteUser(user_id).then(res=>{
          this.listData.splice(index,1)
        })
      },
      filterTag(value, row) {
        return row.role === value;
      }
    }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>
